<template>

    <div class="bg-container">
        <div class="my-header">
            <div class="search-form" v-if="headerShow">
                <a-form size="small" :model="pageData" layout="inline">
                    <a-form-item label="修补工时">
                        <a-select popup-container="html"  :style="{ width: '320px' }" :loading="loading" placeholder="请输入修补工时"
                            @search="handleSearch" v-model="pageData.dropDownData" :filter-option="false" allow-search
                            allow-clear @focus="focusSel">
                            <a-option v-for="item in pageData.DefectNameList" :value="item">{{ item }}</a-option>
                        </a-select>
                    </a-form-item>
                </a-form>
            </div>
              <div class="my-divisders">
            <a-divider orientation="center">
                <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
                   <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
            </a-divider>
             </div>
            <div class="my-tool-bar">
                <Toolbar :items="['查询', '新增', '删除', '导出', '导入']" @add="addHandler" @import="importHandler"
                    @del="deleteHandler" @select="selectHandler" @export="exports" @excel="downloadHandler">
                </Toolbar>
            </div>
        </div>
    </div>

    <div class="gang"></div>

    <div ref="tablediv" style="padding: 10px; box-sizing: border-box;height:100%">
        <a-tabs   :lazy-load="true" :justify="true">
            <a-tab-pane title="验布等级">
                <a-table style="height:100%" :scrollbar="true" sticky-header @page-change="pagination.change" stripe :bordered="true"
                    :columns="tableColumns" :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                    v-model:selected-keys="selectedRowKeys" :loading="table.tableLoading" :data="table.dataList"
                    :pagination="{ size: 'small', current: pagination.page, pageSize: pagination.pageSize, total: pagination.total, showPageSize: false }"
                    :rowKey="rowKey">
                    <template #action="{ record }">
                        <a-button type="primary" size="small" status="warning" @click="editHandler(record)">
                            <template #icon>
                                <icon-edit />
                            </template>
                            修 改
                        </a-button>
                    </template>
                    <template #leJuan="{ record }">
                        <div>{{ record.deleteDonation === 0 ? "是" : "否" }}</div>
                    </template>
                </a-table>
            </a-tab-pane>
        </a-tabs>
    </div>

    <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd"
        unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false"  >
        <template #title>
            {{ pageData.sideTitle }}
        </template>
        <div>
            <a-form ref="formRef" layout="vertical" :model="dataForm">
                <a-form-item label="疵点编号" field="clothtypeCode"
                    :rules="[{ validator: isChiese }, { required: true, message: '疵点编号必填' }]"
                    :validate-trigger="['change', 'blur']">
                    <a-input placeholder="" v-model="dataForm.clothtypeCode" @blur="inputBlur" />
                </a-form-item>
                <a-form-item label="疵点名称" field="defectName" :validate-trigger="['change', 'blur']"
                    :rules="[{ required: true, message: '疵点名称必填' }]">
                    <a-input placeholder="" v-model="dataForm.defectName" />
                </a-form-item>
                <a-form-item label="疵点等级" field="defectGrade" :validate-trigger="['change', 'blur']"
                    :rules="[{ required: true, message: '疵点等级必填' }]">
                    <a-input placeholder="" v-model="dataForm.defectGrade" />
                </a-form-item>
                <a-form-item label="是否乐捐" field="deleteDonation">
                    <a-select popup-container="html"  placeholder="" v-model="dataForm.deleteDonation">
                        <a-option :value="0">是</a-option>
                        <a-option :value="1">否</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="乐捐金额" field="donationMoney">
                    <a-input-number v-model="dataForm.donationMoney" placeholder="" class="input-demo" :min="0"
                        :max="100000000000000000000000000" />
                </a-form-item>
            </a-form>
        </div>
    </a-drawer>

</template>

<script lang="ts">
import { post } from "@/api/http";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";

import { ref, reactive, onMounted, onActivated, onUnmounted } from "vue";
import Toolbar from "@/components/Toolbar.vue";
import { Form, Message, Modal } from "@arco-design/web-vue";
import { FormInstance } from "@arco-design/web-vue/es/form";
import emitter from "@/hooks/useEventBus";
import validate from "@/hooks/useValidate";
import { DatasetComponent } from "echarts/components";
import { baseURL } from '../../../api/axios.config'
import axios from "axios";

interface DefectName {
    "id": any,
    "clothtypeCode": any,
    "defectName": string | undefined,
    "defectGrade": string | undefined,
    "deleteDonation": number | undefined,
    "donationMoney": number | undefined,
    "deleteState": number | undefined,
    "createName": string | undefined,
    "createTime": string | undefined,
    "updateName": string | undefined,
    "updateTime": string | undefined,
}
export default {
    name: "RepairLabor",
    setup() {
        //查询
        const scrollbar = ref(true)
        function doRefresh() {
            pageData.pageLoading = true

            post({
                url: "qms/repairWorktime/selectPage",
                data: {
                    page: pagination.page,
                    size: pagination.pageSize,
                    deleteState: 0,
                    merceryCode: pageData.dropDownData
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {

                        table.handleSuccess(data.list);
                        pagination.setTotalSize(data.total);

                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }
        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        //检验表单是否含有中文的方法
        const hasChiese = validate.includeChinese;
        const tableColumns = useTableColumn([
            {
                title: "编号",
                key: "clothtypeCode",
                dataIndex: "clothtypeCode",
                width: 150
            },
            {
                title: "验布等级",
                key: "defectName",
                dataIndex: "defectName",
                width: 150
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 150
            },
            {
                title: "最后修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150
            },
            {
                title: "最后修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 150
            },
            {
                title: "操作",
                key: "id",
                dataIndex: "id",
                slotName: "action",
                width: 150, fixed: 'right'
            },
        ]);
        const scroll = {
            x: 2000,
            y: 200
        };
        const tablediv = ref(null)
        const pageData = reactive<{
            DefectName: DefectName[]
            showAdd: boolean
            sideTitle: string
            dropDownData: any
            pageLoading: boolean,
            height: number,
            tablediv: any,
            rHeight: number | undefined,
            DefectNameList: []
        }>({
            DefectName: [],
            showAdd: false,
            sideTitle: "新增修补工时",
            dropDownData: "",
            pageLoading: false,
            height: 0,
            tablediv: null,
            rHeight: 0,
            DefectNameList: []
        });
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ "defectName": "" })
        }
        //下拉数据 
        const options = ref<any>(pageData.DefectNameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { defectName: value }
                loading.value = true;
                window.setTimeout(() => {
                    selCxAll(ob);
                    options.value = pageData.DefectNameList;
                    loading.value = false;
                }, 200)
            } else {
                options.value = []
            }
        };
        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "qms/defectType/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data);
                    // (data as string[]).splice(0, 0, "全部");
                    pageData.DefectName = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        onMounted(() => {
            emitter.on("refresh-RepairLabor", () => {
                // doRefresh();
                selCxAll({ "defectName": "" });

            });
            pageData.rHeight = document.getElementById("masterDataSettings")?.clientHeight
            //表格的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight - 200;


            }

            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementById("masterDataSettings")?.clientHeight

                //表格的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight - 200;
                }

            })
        });

        //查询
        const selectHandler = () => {
            doRefresh();
        }
        const queryData = reactive({
            clothType: "",
        });
        const addHandler = () => {
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                } else if (key === "deleteState" || key === "donationMoney" || key === "deleteDonation") {
                    dataForm[key] = 0;
                }
                else {
                    dataForm[key] = "";
                }

            }
            pageData.showAdd = true;
            pageData.sideTitle = "新增修补工时";
        };
        const dataForm = reactive<DefectName>({
            "id": null,
            "clothtypeCode": "",
            "defectName": "",
            "defectGrade": "",
            "deleteDonation": 0,
            "donationMoney": 0,
            "deleteState": 0,
            "createName": "",
            "createTime": "",
            "updateName": "",
            "updateTime": "",
        });
        const formRef = ref<FormInstance>();
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    if (pageData.sideTitle === "新增修补工时") {
                        post({
                            url: "product/pdVerifyclothLevel/insert",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();

                                pageData.showAdd = false;

                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }

                        });
                    } else {
                        post({
                            url: "product/pdVerifyclothLevel/update",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;

                                Message.success({
                                    content: "修改成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }

                        });
                    }
                }
            });
        };
        const deleteHandler = () => {
            if (selectedRowKeys.value.length === 0) {
                return;
            }
            Modal.confirm({
                title: "系统提示",
                content: "确认删除选中的数据?",
                onOk() {
                    post({
                        url: "product/pdVerifyclothLevel/delete",
                        data: selectedRowKeys.value,
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: "删除成功",
                                duration: 5000,
                            });
                            pagination.page = 1
                            doRefresh()
                        } else {
                            Message.error({
                                content: "修改失败",
                                duration: 5000,
                            });
                        }

                    });
                },
            });
        };
        const editHandler = (record: DefectName) => {
            dataForm.id = record.id;
            dataForm.clothtypeCode = record.clothtypeCode;
            dataForm.defectName = record.defectName;
            dataForm.deleteDonation = record.deleteDonation;
            dataForm.defectGrade = record.defectGrade;
            dataForm.donationMoney = record.donationMoney;
            pageData.sideTitle = '修改修补工时'
            pageData.showAdd = true
        };
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })

        }
        //input离开焦点 将小写转大写
        const inputBlur = () => {
            dataForm.clothtypeCode = dataForm.clothtypeCode.toUpperCase();
        }
        //导出
        const exports = () => {
            if (selectedRowKeys.value.length === 0) {
                Message.error('请先勾选')
                return
            } else {
                //将表头拼接出来
                let head = "<th>疵点编号</th><th>疵点名称</th><th>疵点等级</th><th>是否乐捐</th><th>乐捐金额</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return selectedRowKeys.value.indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["clothtypeCode"] + "</td>";
                    body += "<td>" + o["defectName"] + "</td>";
                    body += "<td>" + o["defectGrade"] + "</td>";
                    body += "<td>" + (o["deleteDonation"] == 0 ? "是" : "否") + "</td>";
                    body += "<td>" + o["donationMoney"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '修补工时', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }
        //模板下载
        const downloadHandler = () => {
            window.open(baseURL + '/product/mercery/uploadMerceryModel')
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/qms/clothtype/uploadModel', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        const headerShow = ref<boolean>(true)
        return {
            headerShow,
            scroll,
            scrollbar,
            tablediv,
            downloadHandler,
            importHandler,
            hasChiese,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            editHandler,
            selectHandler,
            options,
            loading,
            handleSearch,
            inputBlur,
            isChiese,
            exports,
            focusSel
        };
    },
    components: { Toolbar },
};
</script>
<style scoped lang="less">



</style>
